//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Cloud.Push
{
    using System;
    using System.Net;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    using ServiceModel.Contract;

    public class BlobStorageProvider : IReadWritePreflightCheckRepository
    {
        private const string DefaultContainerName = "preflightevtdata";
        private readonly IPreflightCheckSerializer serializer;
        private readonly CloudStorageAccount storageAccount;
        private readonly string roleName;
        private readonly string containerName;

        private BlobStorageProvider(IPreflightCheckSerializer serializer, CloudStorageAccount storageAccount, string roleName, string containerName)
        {
            this.serializer = serializer;
            this.storageAccount = storageAccount;
            this.roleName = roleName;
            this.containerName = containerName;
        }

        public void Save(PreflightCheck checkResult)
        {
            var blob = this.GetBlob();
            blob.DeleteIfExists(CreateOptions());
            var blobData = this.serializer.Serialize(checkResult);
            blob.UploadByteArray(blobData, CreateOptions());
        }

        public PreflightCheck GetCheck()
        {
            try
            {
                var blob = this.GetBlob();
                var data = blob.DownloadByteArray(CreateOptions());
                return this.serializer.Deserialize(data);
            }
            catch (StorageClientException exception)
            {                
                if (IsResourceNotFoundException(exception))
                {
                    return null;
                }

                throw;
            }
        }

        private CloudBlob GetBlob()
        {
            var container = GetContainer(this.storageAccount, this.containerName);
            container.CreateIfNotExist(CreateOptions());
            var blob = container.GetBlobReference(this.roleName);
            return blob;
        }

        public static IReadWritePreflightCheckRepository Create(CloudStorageAccount account, string roleName)
        {
            return Create(account, roleName, DefaultContainerName);
        }

        public static IReadWritePreflightCheckRepository Create(CloudStorageAccount account, string roleName, string containerName)
        {
            var container = GetContainer(account, containerName);
            container.CreateIfNotExist();
            return new BlobStorageProvider(new BinaryPreflightCheckSerializer(), account, roleName, containerName);
        }

        private static CloudBlobContainer GetContainer(CloudStorageAccount account, string container)
        {
            var blobClient = account.CreateCloudBlobClient();
            return blobClient.GetContainerReference(container);
        }

        private static bool IsResourceNotFoundException(StorageClientException exception)
        {
            var webException = exception.InnerException as WebException;
            return webException != null &&
                    webException.Response != null &&
                    ((HttpWebResponse)webException.Response).StatusCode == HttpStatusCode.NotFound;
        }

        private static BlobRequestOptions CreateOptions()
        {
            return new BlobRequestOptions
                {
                    RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(5))
                };
        }
    }
}
